<template>
  <div class="container">
    <!--    面包屑导航区-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--    卡片内容列表区域-->
    <el-card class="box-card">
      <!--      添加角色-->
      <el-row >
        <el-col :span="4">
          <el-button @click="addUserDialogVisible = true" type="primary" >添加用户</el-button>
        </el-col>
      </el-row>

      <!--      角色列表区-->
      <el-table
        border
        stripe
        :data="rolesList"
        style="width: 100%">
        <!--        展开列-->
        <el-table-column
          type="expand"
        >
          <template slot-scope="scope">
            <el-row
              v-for="(item1,idx1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',{'bdtop':idx1===0},'vcenter']"
            >
              <!--渲染一级权限-->
              <el-col :span="5" :key="idx1">
                <el-tag closable>
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right">

                </i>
              </el-col>

              <!-- 渲染二级和三级权限-->
              <el-col :span="19">
                <el-row
                  v-for="(item2,idx2) in item1.children"
                  :key="item2.id"
                  :class="[{'bdtop':idx2!==0},'vcenter']"
                >
                  <!--渲染二级权限-->
                  <el-col :span="6">
                    <el-tag closable type="success">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right">

                    </i>
                  </el-col>

                  <!-- 渲染三级权限-->
                  <el-col :span="18">
                    <el-tag v-for="(item3,idx3) in item2.children"
                            :key="item3.id"
                            :class="[{'bdtop':idx3!==0}]"
                            closable
                            type="warning"
                            @close="removeRightsById(scope.row,item3.id)"
                    >
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>z
        <!--        索引列-->
        <el-table-column
          type="index"
          label="#"
        >
        </el-table-column>

        <el-table-column
          prop="roleName"
          label="角色名称"
        >
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        >
        </el-table-column>

        <el-table-column width="300px" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleEditDialogOpen(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              icon="el-icon-delete"
              type="danger"
              @click="handleDelete(scope.row.id)">删除</el-button>
            <el-tooltip :enterable = 'false'  class="item" effect="dark" content="分配角色" placement="top">
              <el-button
                size="mini"
                icon="el-icon-setting"
                type="warning"
                @click="handleSet(scope.row)">分配权限</el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <!--分配角色弹框-->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      @close="setRolesDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
      >

      </el-tree>

      <!--   内容底部区域   >-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights" >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 分配权限对话框是否打开
      setRolesDialogVisible: false,
      // 树形权限列表
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的数数据
      defKeys: [],
      // 角色id
      roleId: ''
    }
  },
  created () {
    // 获取所有的角色
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.$message.success('获取角色列表成功')
    },
    // 根据id删除对应的权限
    removeRightsById (role, rightsId) {
      this.$confirm('此操作将删除该z权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发起编辑用户网络请求
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
        if (res.meta.status !== 200) {
          return this.$message.error('操作失败')
        }
        // 刷新数据列表
        // this.getRolesList()
        role.children = res.data
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配权限对话框
    async handleSet (item) {
      this.roleId = item.id
      // 获取所有权限tree数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data
      this.$message.success('获取权限列表成功')

      // 递归获取三级节点
      this.getDefKeys(item, this.defKeys)
      // 弹出弹框
      this.setRolesDialogVisible = true
    },
    // 通过递归的方法获取三级权限选中的id并保存到defKeys
    getDefKeys (node, arr) {
      // 如果当前节点不含children属性说明是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getDefKeys(item, arr)
      })
    },

    // 监听分配权限对话框关闭
    setRolesDialogClosed () {
      this.defKeys = []
    },

    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限失败')
      }
      this.rightsList = res.data
      this.$message.success('更新权限成功')
      this.getRolesList()
      this.setRolesDialogVisible = false
    }

  }
}
</script>

<style scoped>

</style>
